<template>
  <div class="list">
    <PageHeader title="轮播图管理" hidden-breadcrumb>
      <template #action>
        <Button type="primary" @click="add">添加</Button>
      </template>
    </PageHeader>

    <Table class="table" border ref="selection" :columns="columns" :data="data">
      <template #image="{ row }">
        <Image
          :src="row.url"
          width="260px"
          :alt="row.title"
          fit="fill"
          preview
          :preview-list="[row.url]"
        />
      </template>
      <template #status>
        <Switch v-model="data.status"></Switch>
      </template>
      <template #options="{ row, index }">
        <div class="options">
          <Button type="primary" @click="update(row, index)">编辑</Button>
          <Button type="error" @click="remove(row._id, index)">删除</Button>
        </div>
      </template>
    </Table>
    <Edit
      v-model="showEdit"
      :editData="editData"
      @add="(v) => data.push(v)"
      @update="(v) => (data[uIndex] = v)"
    />
  </div>
</template>

<script>
import { list, remove } from "@/api/banner";
import Edit from "./Edit.vue";

export default {
  name: "BannerList",
  data() {
    return {
      showEdit: false,
      editData: null,
      uIndex: -1,
      columns: [
        {
          title: "名字",
          key: "title",
          width: 300,
        },
        {
          title: "图片",
          key: "url",
          slot: "image",
          width: 300,
        },
        {
          title: "跳转地址",
          key: "path",
        },
        {
          title: "排序",
          key: "sort",
        },
        {
          title: "开启",
          key: "status",
          slot: "status",
        },
        {
          title: "描述",
          key: "desciption",
          width: 300,
        },
      ],
      data: [],
    };
  },
  components: { Edit },
  created() {
    this.columns.push({
      title: "操作",
      slot: "options",
      width: "200px",
      align: "center",
    });
    list().then((res) => {
      this.data = res.data.data;
    });
  },
  methods: {
    add() {
      this.showEdit = true;
      this.editData = { _id: "" };
    },
    update(row, index) {
      this.editData = row;
      this.uIndex = index;
      this.showEdit = true;
    },
    remove(_id, index) {
      remove(_id).then((res) => {
        if (res.data.errCode == 0) {
          this.data.splice(index, 1);
          this.$Notice.success({
            title: "删除成功",
          });
        } else {
          this.$Notice.error({
            title: "未知原因删除失败",
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.list {
  width: 100%;
  margin: 0 10px;
  padding: 10px;
  margin-top: 50px;
}
.table {
  margin-top: 20px;
}
.options {
  display: flex;
  justify-content: space-around;
}
</style>